import { Component, Input, OnInit } from '@angular/core';
import { missing, replaceAll } from '../../../utils/utils';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { SubjectService } from '@core/services/events/subject.service';

@Component({
  selector: 'apes-status-bar',
  template: `
    <button class="{{prefixCls}}-btn {{prefixCls}}-bar-button"
            *ngFor="let data of statusBar"
            disabled="disabled"
            [class.button-active]="setStyle(data)"
    >
      {{data.label}}
    </button>
  `,
})
export class ApesStatusBarComponent implements OnInit {

  // [class.button-done]="setStyle(data)"
  // [class.button-active]="setStyle(data)"
  // [class.button-disabled]="setStyle(data)"

  @Input() ctx = {};

  @Input() btnStatusMetadata = [];

  prefixCls = 'apes-status';
  statusBar = [];

  constructor(private expressionService: ExpressionService, protected subject: SubjectService) {
  }

  ngOnInit() {
    this.subject.subscribe(this.ctx, this.subject.event_form_button, data => {
      this.statusBar = this.btnStatusMetadata.filter(metadata => {
        if (missing(metadata.hide)) return true;
        return !this.evaluate(metadata.hide);
      });
    });

    this.subject.subscribe(this.ctx, this.subject.event_form_refresh, data => {
      this.statusBar = this.btnStatusMetadata.filter(metadata => {
        if (missing(metadata.hide)) return true;
        return !this.evaluate(metadata.hide);
      });
    });
  }

  setStyle(metadata: any): boolean {
    if (missing(metadata.states)) return true;
    return this.evaluate(metadata.states);
  }

  evaluate(expression: string | boolean) {
    return this.expressionService.eval(typeof expression === 'boolean' ? JSON.stringify(expression) : replaceAll(expression, '\'', '"'), {
      context: this.ctx,
      model: this.ctx['model'],
    });
  }

}

